PHP cheat sheet

This link will take you to the W3 Schools, a fantastic resource for PHP and other cool stuff.

Type this... ... to get this
 
 
In the PHP file:
<?php echo "This is my first PHP file!"; ?>
If you right click on the resulting page and do an Inspect, you will see this:
<html>   <head></head>   <body>This is my first PHP file!</body> </html>
 

Click on this link to see the result of the code on the left.

 
<!DOCTYPE html> <html>     <head>         <meta charset="utf-8">         <title>Embed PHP in HTML</title>     </head>     <body>         <h1>Embed PHP in HTML</h1>         <p> <?php     echo "If you can keep your head when all about you are losing theirs"; ?>         </p> <?php     echo "<p>If you can trust yourself when all men doubt you</p>"; ?>     </body> </html>  

Click on this link to see the result of the code on the left.

 
<!DOCTYPE html> <html>     <head>         <meta charset="utf-8">         <title>Using variables in PHP</title>         <meta http-equiv="X-UA-Compatible" content="IE=edge">         <meta name="viewport" content="width=device-width, initial-scale=1">     </head>     <body>        <div class="container-fluid">           <h1>Variables</h1>           <h2>First look at using variables:</h2> <?php $univ = "Concordia"; $year = 1992; echo "I have been working at " . $univ . " since " . $year . "! "; define("country", "Canada"); echo "We're in " . country . "."; ?>           <h2>Numeric variables:</h2> <?php $x = 7; var_dump($x); $y = 3; $z = $x+$y; echo "<br />"; echo $z; $z = 0x1A; echo "<br />"; var_dump($z); $w = 0123; echo "<br />"; var_dump($w); $floatingNumber = 3.7; echo "<br />"; var_dump($floatingNumber); ?>           <h2>Boolean variables:</h2> <?php $booleanVariable1 = (5<6); $booleanVariable2 = (3>5); $booleanVariable3 = $booleanVariable1 || $booleanVariable2; var_dump($booleanVariable1); echo "<br />"; var_dump($booleanVariable2); echo "<br />"; var_dump($booleanVariable3); echo "<br />"; var_dump(!$booleanVariable1); ?>           <h2>Array variables:</h2> <?php $carmakes = array("Audi", "BMW", "Mercedes"); echo "<p>Car makes:</p>"; print_r($carmakes); echo "<p>Car makes: Element one</p>"; echo $carmakes[0]; //Associative Arrays $shoppingBasket1 = array("a"=>"bread", "b"=>"milk", "c"=>"eggs"); $shoppingBasket2 = array("b"=>"milk", "a"=>"bread", "c"=>"eggs"); $shoppingBasket3 = array("d"=>"yogurt", "e"=>"orange", "f"=>"apple"); $shoppingBasket = $shoppingBasket1 + $shoppingBasket3; echo "<p>Shopping Basket:</p>"; print_r($shoppingBasket1); echo "<br />"; var_dump($shoppingBasket1); echo "<p>shoppingBasket1 == shoppingBasket2</p>"; var_dump($shoppingBasket1 == $shoppingBasket2); echo "<p>shoppingBasket1 === shoppingBasket2</p>"; var_dump($shoppingBasket1 === $shoppingBasket2); echo "<p>Basket 3</p>"; print_r($shoppingBasket3); echo "<p>shoppingBasket1<> shoppingBasket3</p>"; var_dump($shoppingBasket1 != $shoppingBasket3); echo "<p>shoppingBasket1 + shoppingBasket3</p>"; print_r($shoppingBasket1 + $shoppingBasket3); ?>           <h2>Object variables:</h2> <?php class car{     //properties     public $make = "Ford";     private $status = "off";          //methods     function turn_on(){      $this->status = "on";               }     function getStatus(){         return $this->status;       } } $myCar = new car; var_dump($myCar); echo "<br />"; echo $myCar->make; echo "<br />"; $myCar->turn_on(); var_dump($myCar); echo "<br />"; echo $myCar->getStatus(); ?>           <h2>Resource variables:</h2> <?php $myFile = fopen("PHP-03.txt","r"); var_dump($myFile); echo "<br />"; echo "Reading just a few characters from the file: "; echo fread($myFile,5); echo "<br />"; echo "Reading the entire file: "; echo fread($myFile,filesize("PHP-03.txt")); ?>             </div>         <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>     </body> </html>  

Click on this link to see the result of the code on the left.

 
<!DOCTYPE html> <html>     <head>         <meta charset="utf-8">         <title>String functions</title>     </head>     <body>         <h1>String functions</h1>         <p> <?php $message = "A man, a plan, a canal: Panama!"; echo "Length of my message: " . strlen($message); echo "<br />"; echo "My message contains " . str_word_count($message) . " words."; echo "<br />"; echo str_replace("an", "oss", $message, $number_of_words_replaced); echo "<br />"; echo "Number of words replaced: " . $number_of_words_replaced . " words."; echo "<br />"; echo "Can you read from the right? <br />" . strrev($message); ?>         </p>     </body> </html>  

Click on this link to see the result of the code on the left.

 
<!DOCTYPE html> <html>     <head>         <meta charset="utf-8">         <title>Conditional operators</title>     </head>     <body>        <div class="container-fluid">           <p> <?php //Basic if format $boolean_variable = true; if ($boolean_variable) {     echo "<p>The boolean variable is true.</p>"; } else {     echo "<p>The boolean variable is false.</p>"; }; //Another way to do a condition $x = ($boolean_variable)?"True branch":"False branch"; echo $x; //Here with elseif $temperature = 25; if ($temperature < 15) {     echo "<p>It is cold!</p>"; } elseif ($temperature>30) {     echo "<p>It is hot!</p>"; } else {     echo "<p>The temperature is just right.</p>"; }; //Here using a case $fieldofstudy = "Math"; switch ($fieldofstudy ) {     case "Math":         echo "<p>Pi is the ratio of the circumference of a circle to its diameter.</p>";         break;     case "Physics":         echo "<p>Pi is 3.14159 plus or minus 0.000005.</p>";         break;     case "Engineering":         echo "<p>Pi is about 22/7.</p>";         break;     default:         echo "<p>Pie is a delicious food.</p>";         break; } ?>           </p>        </div>     </body> </html>  

Click on this link to see the result of the code on the left.

 
<!DOCTYPE html> <html>     <head>         <meta charset="utf-8">         <title>Loops</title>     </head>     <body>        <div class="container-fluid">           <p> <?php //for loops    echo "Examples using for loops: <br /><br />";      for($i = 1; $i <= 7; $i++){     echo $i . "<br />";    }    echo "<br />";      $universities = array("Concordia", "McGill", "UQAM", "UdM");    foreach($universities as $value){       echo $value . "<br />";      }    echo "<br />";      $software = array("ps"=>"PeopleSoft", "pa"=>"Power Automate", "js"=>"JavaScript");    foreach($software as $key=>$value){       echo $key . " : " . $value . "<br />";    }    echo "<br />-----------------------------------------------<br /><br />";   //while loops    echo "Examples using while loops: <br /><br />";      $i = 1;    while($i <= 7){       echo $i . "<br />";       $i++;    }    echo "<br />";      $software = array("PeopleSoft", "Power Automate", "JavaScript");    $j = 0;    while($j<3){       echo $software [$j] . "<br />";       $j++;    } ?>           </p>        </div>     </body> </html>  

Click on this link to see the result of the code on the left.

 
<!DOCTYPE html> <html>     <head>         <meta charset="utf-8">         <title>Functions</title>     </head>     <body>        <div class="container-fluid">           <p> <?php    function introduction(){       echo "<p>This is Concordia University!</p>";    }    function location($university, $city){       echo "<p>$university is located in $city.</p>";    }    function sum($x, $y){       return $x + $y;    }    introduction();    location("Concordia", "Montreal");    $sum = sum(2, 3);    echo "<p>The sum of 2 and 3 is $sum.</p>"; ?>           </p>        </div>     </body> </html>  

Click on this link to see the result of the code on the left.

 
<!DOCTYPE html> <html>     <head>         <meta charset="utf-8">         <title>Get and Post methods</title>     </head>     <body>        <div class="container-fluid"> <?php echo "<h3>GET:</h3>"; print_r($_GET); if($_GET["submit"]){     if($_GET["username"]) {         echo "<p>Hi ". $_GET["username"] . " . Welcome to my page!</p>";       } } echo "<h3>POST:</h3>"; print_r($_POST); if($_POST["submit"]){     if($_POST["country"]){         echo "<p>Your Country is: " . $_POST["country"] . ".</p>";       } } ?>           <br /><br />           <form method="get" action="PHP-08.php">              <label for="username">Enter your name here and press the submit button: </label><br />              <input type="text" name="username" id="username">              <input type="submit" name="submit" value="Submit">           </form>           <br />           <form method="post" action="PHP-08.php">              <label for="country">Enter your country of origin here and press the submit button: </label><br />              <input type="text" name="country" id="country">              <input type="submit" name="submit" value="Submit">           </form>        </div>     </body> </html>  

Click on this link to see the result of the code on the left.

 
<!DOCTYPE html> <html>     <head>         <meta charset="utf-8">         <title>Array functions</title>     </head>     <body>        <div class="container-fluid"> <?php $deptList1 = array("IITS", "UCS", "HR", "IITS"); $deptList2 = array("FAO", "SGS", "Library"); $deptList = array_merge($deptList1, $deptList2); echo "<p>List of departments:</p>"; print_r($deptList); echo "<p>Number of items in list of departments: </p>" . count($deptList); $count = array_count_values($deptList); echo "<p>Dept Count</p>"; print_r($count); echo "<p>Number of IITS iteams in list: </p>" . $count["IITS"]; if(in_array("IITS", $deptList)){     echo "<p>There is a department calleed IITS in the university.</p>"; }else{     echo "<p>There is no department calleed IITS in the university.</p>"; } array_push($deptList, "Marketing"); echo "<p>Dept list after adding Marketing: </p>"; print_r($deptList); if($_GET["submit"]){     if($_GET["item"]){         array_push($deptList, $_GET["item"]);     } } echo "<p>Dept list:</p>"; print_r($deptList); array_splice($deptList, 0, 4,array("Accountancy", "Hospitality")); echo "<p>Dept list:</p>"; print_r($deptList); sort($deptList); echo "<p>Dept list sorted in ascending order:</p>"; print_r($deptList); $countries = array("CH"=>"Swiztzerland", "DE"=>"Germany", "UK"=>"Great Britain"); echo "<p>Countries:</p>"; print_r($countries); asort($countries); echo "<p>Countries sorted in ascending order by value:</p>"; print_r($countries ); ksort($countries); echo "<p>Countries sorted in ascending order by keys:</p>"; print_r($countries); ?>           <br />           <br />           <form method="get">              <label for="item">Add item to dept list:</label>              <input type="text" name="item" id="item">              <input type="submit" name="submit" value="Submit">           </form>        </div>     </body> </html>  

Click on this link to see the result of the code on the left.

 
<!DOCTYPE html> <html>     <head>         <meta charset="utf-8">         <title>Date and Time</title>         <style>             h1{                 color:green;               }             h3{                 color:purple;               }         </style>     </head>     <body>        <div class="container-fluid">           <div class="row">              <div class="col-sm-offset-1 col-sm-10">                 <h1>Date and Time</h1>                 <div>                    <h3>Date using the date() function:</h3> <?php //Formatting the Dates and Times with PHP // Day of the month:     //d (01/31)->two digits with leading zeros     //j (1/31)->without leading zeros // Day of the week:     //D (Mon/Sun)->text as an abbreviation     //l (monday)->full lowercase     //L (MONDAY)->full uppercase // Month:     //m (01/12)->two digits with leading zeros     //M (Jan)->text as an abbreviation     //F (January)-> Full month // Year:     //y (09/15)->two digits     //Y (2009-2015)->Four Digits // Separators:     //hyphens: (-)     //dots: (.)     //slashes: (/)     //spaces: ( ) $today = date("M j, Y"); echo "<p>Today is: $today.</p>"; ?>                 <h3>Time using the date() function:</h3> <?php //format the time string: //hour:     //h (01-12)->12-hour format with leading zeros     //H (00-24)->24-hour format with leading zeros //minutes:     //i (01-59)->minutes with leading zeros //seconds:     //s (01-59) ->seconds with leading zeros //Ante meridiem and Post meridiem     //a->lowercase     //A->uppercase $today = date("H:i:s A"); echo "<p>Time is: $today.</p>"; ?>                 <h3>Current timestamp using time() function:</h3> <?php $timestamp = time(); echo "<p>Timestamp is : $timestamp</p>"; ?>                 <h3>Convert timestamp to time:</h3> <?php $time = date("F d, Y h:i:s A", $timestamp); echo "<p>Time is $time.</p>"; ?>                 <h3>Date in 100 days from now:</h3> <?php $timestamp = mktime(0, 0, 0, date("m"), date("d")+100, date("Y")); $time = date("D d M, Y", $timestamp); echo "<p>Date in 100 days from now: $time.</p>"; ?>                 </div>              </div">           </div>        </div>     </body> </html>  

Click on this link to see the result of the code on the left.

Volta à página principal do Valdir


Críticas, comentários e sugestões sobre esta página podem ser enviados para este endereço: valdir.jorge@gmail.com
Esta página foi atualizada pela última vez em 30 de junho de 2022
http://mypage.concordia.ca/alcor/vjorge/paginas/valdir/Escolinha%20de%20PHP.html